package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"proj-manage/cache"
	"proj-manage/modlers"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	var data = modlers.Article{
		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := modlers.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	var article modlers.Article
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	modlers.DB.Where("id = ?", data.ID).Find(&article)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {

	id := c.Query("id")

	err := modlers.DB.Where("id =?", id).Delete(&modlers.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {

	var article []modlers.Article
	modlers.DB.Find(&article)

	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modlers.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": article,
		"msg":  "ok",
	})
	return

}
